<template>
  <a-card :bordered="false">
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="shouldPayFlag != '1' && !disabled">
      <a-button @click="handleAdd" type="primary" icon="plus" :disabled="isDisabledAuth('erpOmcContractPlanTask:add')">新增</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="index"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange">
        <template slot="status" slot-scope="status">
          <a-badge :status="status | statusTypeFilter" :text="status | statusFilter"/>
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record, index" v-if="shouldPayFlag != '1' && !disabled">
          <a-button
            class="ruleButton"
            :ghost="true"
            type="primary"
            icon="edit"
            @click="handleEdit(record)"
            :disabled="isDisabledAuth('erpOmcContractPlanTask:edit')"
          />
          <a-divider type="vertical" v-if="shouldPayFlag != '1' && !disabled"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(index)" v-if="shouldPayFlag != '1' && !disabled">
            <a-button
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="delete"
              :disabled="isDisabledAuth('erpOmcContractPlanTask:delete')"/>
          </a-popconfirm>
        </span>

      </a-table>
    </div>

    <ErpOmcTaskRedistributionPlanTaskModal ref="modalForm" @dataOne="dataOne" @ok="modalFormOk"></ErpOmcTaskRedistributionPlanTaskModal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import ErpOmcTaskRedistributionPlanTaskModal from './ErpOmcTaskRedistributionPlanTaskModal'
  import { filterObj } from '@/utils/util'
  import { getAction } from '@/api/manage'
  import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  import Vue from 'vue'
  export default {
    name: 'ErpOmcTaskRedistributionPlanTaskList',
    mixins: [mixinDevice, DisabledAuthFilterMixin],
    components: {
      ErpOmcTaskRedistributionPlanTaskModal
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      projectId: {
        type: [Number, String],
        default: '',
        required: false
      },
      // 款项的金额
      totalPrice: {
        type: [Number, String],
        default: '',
        required: false
      },
      // 合同金额
      bchte: {
        type: Number,
        default: 0
      },
      // 应收状态
      shouldPayFlag: {
        type: [String, Number],
        default: ''
      },
      // 分配任务信息列表
      redistributionDtList: {
        type: [Array],
        default: () => []
      }
    },
    data () {
      return {
        description: '任务对应合同款项流程表管理页面',
        planId: '', // 收付款计划id
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [],
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 100,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',
        // 表头
        columns: [],
        // 列设置
        settingColumns: [],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '生产团队',
            align: 'center',
            dataIndex: 'productTeamName'
          },
          {
            title: '业务名称',
            align: 'center',
            dataIndex: 'categoryName'
          },
          {
            title: '任务说明',
            align: 'center',
            dataIndex: 'taskDesc'
          },
          {
            title: '款项分配占比(%)',
            align: 'center',
            dataIndex: 'paymentRate'
          },
          {
            title: '款项分配金额(元)',
            align: 'center',
            dataIndex: 'paymentMoney'
          },
          // {
          //   title:'任务id',
          //   align:"center",
          //   dataIndex: 'taskId',
          // },
          // {
          //   title:'收付款计划id',
          //   align:"center",
          //   dataIndex: 'planId',
          // },
          // {
          //   title:'档案id',
          //   align:"center",
          //   dataIndex: 'planFinalId',
          // },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 160,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: '/api/erp/omc/contractmanager/erpOmcContractPlanTask/list',
          delete: '/api/erp/omc/contractmanager/erpOmcContractPlanTask/delete',
          deleteBatch: '/api/erp/omc/contractmanager/erpOmcContractPlanTask/deleteBatch',
          exportXlsUrl: '/api/erp/omc/contractmanager/erpOmcContractPlanTask/exportXls',
          importExcelUrl: '/api/erp/omc/contractmanager/erpOmcContractPlanTask/importExcel'
        },
        dictOptions: {},
        superFieldList: []
      }
    },
    created() {
      // 加载数据字典信息
      this.initDictConfig();
      this.getSuperFieldList();
      if (!this.disableMixinCreated) {
        this.initColumns()
      }
      if (this.disabled && this.shouldPayFlag == '1') {
        this.defColumns.pop()
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          '0': '待提交',
          '1': '待审核',
          '2': '已审核'
        }
        return statusMap[status] || status
      },
      statusTypeFilter(type) {
        const statusTypeMap = {
          '0': 'success',
          '1': 'success',
          '2': 'success'
        }
        return statusTypeMap[type] || 'success'
      }
    },
    computed: {
      importExcelUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    methods: {
      initDictConfig() {
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'productTeam', res.result)
          }
        })
      },
      loadData(arg, id) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        if (id) {
          this.params.billId = id
        }
        this.loading = true
        getAction(this.url.list, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
            this.onData()
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        // TODO 字段权限控制
        var str = 'id'
        this.columns.forEach(function (value) {
          // 多表头字段
          if (value.dataIndex == null && value.dataIndex === undefined) {
            value.children.forEach(function (item) {
              str += ',' + item.dataIndex.replace('_dictText', '')
            })
          } else {
            str += ',' + value.dataIndex
          }
        })
        return str
      },

      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },
      handleDelete: function (key) {
        if (this.dataSource.length == 1) {
          this.dataSource = []
          return
        }
        this.dataSource.splice(key, 1);
        this.dataSource.forEach((item, index) => {
          item.key = index
          let paymentRate = item.paymentRate
          item.paymentMoney = (this.totalPrice * paymentRate / 100).toFixed(2)
        })
      },
      handleAdd: function () {
        this.$refs.modalForm.redistributionDtList = this.redistributionDtList
        this.$refs.modalForm.add()
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.projectId = this.projectId
        this.$refs.modalForm.totalPrice = this.totalPrice
        this.$refs.modalForm.planId = this.planId
        this.$refs.modalForm.disableSubmit = false
      },
      handleEdit: function (record) {
        // debugger;
        this.$refs.modalForm.redistributionDtList = this.redistributionDtList
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.projectId = this.projectId
        this.$refs.modalForm.totalPrice = this.totalPrice
        this.$refs.modalForm.planId = this.planId
        this.$refs.modalForm.disableSubmit = false
      },
      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.loadData()
        // 清空列表选中
        this.onClearSelected()
      },
      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.columns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.columns = cols
          }
        }
      },
      dataOne(data, flag) {
        if (flag) {
          this.dataSource.push(data)
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          this.dataSource.splice(data.key, 1, data);
        }
      },
      submitForm() {
        return this.dataSource
      },
      getSuperFieldList() {
        let fieldList = [];
        fieldList.push({ type: 'string', value: 'taskId', text: '任务id', dictCode: '' })
        fieldList.push({ type: 'string', value: 'planId', text: '收付款计划id', dictCode: '' })
        fieldList.push({ type: 'string', value: 'planFinalId', text: '档案id', dictCode: '' })
        fieldList.push({ type: 'BigDecimal', value: 'paymentRate', text: '款项占比', dictCode: '' })
        fieldList.push({ type: 'BigDecimal', value: 'paymentMoney', text: '款项分配金额', dictCode: '' })
        fieldList.push({ type: 'string', value: 'productTeam', text: '生产团队', dictCode: '' })
        fieldList.push({ type: 'string', value: 'categoryName', text: '业务分类', dictCode: '' })
        fieldList.push({ type: 'Text', value: 'taskDesc', text: '任务说明', dictCode: '' })
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
